package com.baidu.controller;


import com.alibaba.dubbo.config.annotation.Reference;
import com.baidu.constant.MessageConstant;
import com.baidu.entity.Result;
import com.baidu.service.*;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.data.JRAbstractBeanDataSource;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("/report")
public class ReportController {
	@Reference
	private MemberService memberService;

	@Reference
	private SetMealService setMealService;

	@Reference
	private ReportService reportService;
	@Reference
    private OrderService orderService;

	/**
	 * 会员数量统计
	 *
	 * @return
	 */

	@RequestMapping("/getMemberReport")
	public Result getMemberReport() {

//	我们要返回一个map集合，里面存的有月份，还有每个月对应的会员数量
		HashMap<String, Object> map = null;//集合转为json数据是一个数组
		try {
			map = new HashMap<>();

			Calendar calendar = Calendar.getInstance();
//	现在往后推12个月。
			calendar.add(calendar.MONTH, -12);

			ArrayList<String> listM = new ArrayList<>();

			SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy.MM");
			for (int i = 0; i < 12; i++) {
				//依次加一个月
				calendar.add(calendar.MONTH, 1);
				String string = dateFormat.format(calendar.getTime());
				listM.add(string);

			}
			map.put("months", listM);

			ArrayList<Integer> mebCount = memberService.findMemberByMonth(listM);
			map.put("memberCount", mebCount);
		} catch (Exception e) {
			return new Result(false, MessageConstant.GET_MEMBER_NUMBER_REPORT_FAIL);

		}
		return new Result(true, MessageConstant.GET_MEMBER_NUMBER_REPORT_SUCCESS, map);
	}
    /**
     * 获取本周预约数
     */
    @RequestMapping("/getOrderCountReport")
    public Result getOrderCountReport() {

//	我们要返回一个map集合，里面存的有月份，还有每个月对应的会员数量
        HashMap<String, Object> map = null;//集合转为json数据是一个数组
        try {
            map = new HashMap<>();
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
            Calendar cld = Calendar.getInstance();
            //定义List存本周日期
            ArrayList<String> listW = new ArrayList<>();
            cld.setFirstDayOfWeek(Calendar.MONDAY);//以周一为首日
            cld.setTimeInMillis(System.currentTimeMillis());//当前时间
            cld.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);//周一
            listW.add(df.format(cld.getTime()));
            for (int i=0;i<6;i++){
                cld.add(cld.DATE,1);
                listW.add(df.format(cld.getTime()));
            }
//            Calendar calendar = Calendar.getInstance();
////	现在往后推12个月。
//            calendar.add(calendar.SUNDAY, -7);
//
//            ArrayList<String> listM = new ArrayList<>();
//
//            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy.MM");
//            for (int i = 0; i < 7; i++) {
//                //依次加一个月
//                calendar.add(calendar.MONTH, 1);
//                String string = dateFormat.format(calendar.getTime());
//                listM.add(string);
//
//            }
            map.put("week", listW);

            ArrayList<Integer> orderCount = orderService.findOrderByWeek(listW);
            map.put("orderCount", orderCount);
        } catch (Exception e) {
            return new Result(false, MessageConstant.GET_ORDERCOUNT_FAIL);

        }
        return new Result(true, MessageConstant.GET_ORDERCOUNT_SUCCESS, map);
    }
	/**
	 * 获得套餐数据报告
	 *
	 * @return
	 */
	@RequestMapping("/reportSetMeal")

	public Result getReportSetMeal() {

		try {
			List<Map<String, Object>> list = setMealService.findSetMealCount();
			/*
			 * 模拟数据
			 * list1：map1.put（“name”,"全家套餐）
			 *           map1.put（“value”,"5”）；
			 *
			 *
			 * list2：map2.put("name","情侣套餐")
			 *        map2.put("value","6")
			 *
			 *
			 * */


			HashMap<String, Object> hashMap = new HashMap<>();
			hashMap.put("setMealCount", list);


			ArrayList<String> setMealName = new ArrayList<>();

			for (Map<String, Object> map : list) {

				String name = (String) map.get("name");
				setMealName.add(name);
			}
			hashMap.put("setMealName", setMealName);

			return new Result(true, MessageConstant.GET_SETMEAL_COUNT_REPORT_SUCCESS, hashMap);
		} catch (Exception e) {
			return new Result(false, MessageConstant.GET_SETMEAL_COUNT_REPORT_FAIL);

		}

	}

	/**
	 * 获得商业报告数据
	 *
	 * @return
	 */
	@RequestMapping("/getBusinessReportData")
	public Result getBusinessReportData() {
		//使用模拟数据

		try {
			Map<String, Object> map = reportService.getBusinessReportData();
			return new Result(true, MessageConstant.GET_BUSINESS_REPORT_FAIL, map);
		} catch (Exception e) {
			return new Result(false, MessageConstant.GET_BUSINESS_REPORT_FAIL);
		}


	}

	/**
	 * 导出Excel模型数据
	 *
	 * @return
	 */
	@RequestMapping("/exportBusinessReport")
	public Result exportBusinessReport(HttpServletResponse response, HttpServletRequest request) {

		try {
			Map<String, Object> map = reportService.getBusinessReportData();
			//取出map的数据结果，填写到Excel相应的单元格。
			String reportDate = (String) map.get("reportDate");
			Integer todayNewMember = (Integer) map.get("todayNewMember");
			Integer totalMember = (Integer) map.get("totalMember");
			Integer thisWeekNewMember = (Integer) map.get("thisWeekNewMember");
			Integer thisMonthNewMember = (Integer) map.get("thisMonthNewMember");
			Integer todayOrderNumber = (Integer) map.get("todayOrderNumber");
			Integer todayVisitsNumber = (Integer) map.get("todayVisitsNumber");
			Integer thisWeekOrderNumber = (Integer) map.get("thisWeekOrderNumber");
			Integer thisWeekVisitsNumber = (Integer) map.get("thisWeekVisitsNumber");
			Integer thisMonthOrderNumber = (Integer) map.get("thisMonthOrderNumber");
			Integer thisMonthVisitsNumber = (Integer) map.get("thisMonthVisitsNumber");
			List<Map<String, Object>> hotSetmeal = (List<Map<String, Object>>) map.get("hotSetmeal");


			//获取Excel模板文件在服务器的真实路进?。
			String filePath = request.getSession().getServletContext().getRealPath("template") + File.separator + "report_template.xlsx";
			//基于模板创建一个Excel表格供下载
			XSSFWorkbook workBook = new XSSFWorkbook(new File(filePath));
			XSSFSheet sheet = workBook.getSheetAt(0);

			XSSFRow row = sheet.getRow(2);
			XSSFCell cell = row.getCell(5);
			cell.setCellValue(reportDate);

			row = sheet.getRow(4);
			cell = row.getCell(5);
			cell.setCellValue(todayNewMember);

			row = sheet.getRow(5);
			row.getCell(5).setCellValue(thisWeekNewMember);//本周新增会员数
			row.getCell(7).setCellValue(thisMonthNewMember);//本月新增会员数

			row = sheet.getRow(7);
			row.getCell(5).setCellValue(todayOrderNumber);//今日预约数
			row.getCell(7).setCellValue(todayVisitsNumber);//今日到诊数

			row = sheet.getRow(8);
			row.getCell(5).setCellValue(thisWeekOrderNumber);//本周预约数
			row.getCell(7).setCellValue(thisWeekVisitsNumber);//本周到诊数

			row = sheet.getRow(9);
			row.getCell(5).setCellValue(thisMonthOrderNumber);//本月预约数
			row.getCell(7).setCellValue(thisMonthVisitsNumber);//本月到诊数

			int rowNum = 12;
			for (Map map1 : hotSetmeal) {//热门套餐
				String name = (String) map1.get("name");
				Long setmeal_count = (Long) map1.get("setmeal_count");

				BigDecimal proportion = (BigDecimal) map1.get("proportion");
				row = sheet.getRow(rowNum++);
				row.getCell(4).setCellValue(name);//套餐名称
				row.getCell(5).setCellValue(setmeal_count);//预约数量
				row.getCell(6).setCellValue(proportion.doubleValue());//占比
			}

			//使用输出流进行表格下载，基于浏览器进行客户端下载。指定以附件的形式下载。
			//? 他是怎样写会客户端的?

			ServletOutputStream outputStream = response.getOutputStream();
			response.setContentType("application/vnd.ms-excel");
			response.setHeader("content-Disposition", "attachment;filename=report.xlsx");//指定以附件形式进行下载

			workBook.write(outputStream);//这一步操作不是很明白？
			outputStream.flush();
			outputStream.close();
			workBook.close();
			return null;
		} catch (Exception e) {
			return new Result(false, MessageConstant.GET_BUSINESS_REPORT_FAIL);
		}


	}


	/**
	 * 导出PDF模型数据
	 *
	 * @return
	 */
	@RequestMapping("/exportBusinessReport4PDF")
	public Result exportBusinessReport4PDF(HttpServletResponse response, HttpServletRequest request) {
		/*
		 * 为什么要编译jasper.jxml文件编译成二进制文件？
		 * 之前的Excel模板就不用编译成二进制文件。
		 * */


		try {
			//1.获得Jasper模板的服务器真实路径，和编译后的.jasper文件的真是路径
			String jrxmlPath = request.getSession().getServletContext().getRealPath("template" + File.separator + "health_business3.jrxml");
			String jasperPath = request.getSession().getServletContext().getRealPath("template" + File.separator + "health_business3.jasper");//编译后的二进制文件

			//2.编译
			JasperCompileManager.compileReportToFile(jrxmlPath, jasperPath);


			//3..取出相应的填充数据。
			Map<String, Object> map = reportService.getBusinessReportData();
			List<Map<String, Object>> hotSetmeal = (List<Map<String, Object>>) map.get("hotSetmeal");

			//4.进行填充
			JasperPrint jasperPrint = JasperFillManager.fillReport(jasperPath, map, new JRBeanCollectionDataSource(hotSetmeal));

			//5.获得response的输出流向客户端写出数据，以下载的附件形式。
			ServletOutputStream out = response.getOutputStream();
			response.setContentType("application/pdf");
			response.setHeader("content-Disposition", "attachment;filename=report.pdf");//指定以附件形式进行下载

			//6.输出文件
			JasperExportManager.exportReportToPdfStream(jasperPrint, out);
			out.flush();
			out.close();
			return null;
		} catch (Exception e) {
			return new Result(false, MessageConstant.GET_BUSINESS_REPORT_FAIL);
		}


	}


}
